package com.csust.automaticteach.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csust.automaticteach.common.ResultUtils;
import com.csust.automaticteach.exception.ErrorCode;
import com.csust.automaticteach.exception.ThrowUtils;
import com.csust.automaticteach.model.dto.exercisessets.ExercisesSetsQueryRequest;
import com.csust.automaticteach.model.entity.ExercisesSets;
import com.csust.automaticteach.model.entity.SetExercises;
import com.csust.automaticteach.model.entity.User;
import com.csust.automaticteach.model.vo.exercises.ExercisesVO;
import com.csust.automaticteach.service.ExercisesService;
import com.csust.automaticteach.service.ExercisesSetsService;
import com.csust.automaticteach.mapper.ExercisesSetsMapper;
import com.csust.automaticteach.service.SetExercisesService;
import com.csust.automaticteach.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.csust.automaticteach.constant.OrderConstant.ASC;

/**
* @author 钰玟
* @description 针对表【t_exercises_sets(套题表)】的数据库操作Service实现
* @createDate 2025-07-23 20:16:17
*/
@Service
public class ExercisesSetsServiceImpl extends ServiceImpl<ExercisesSetsMapper, ExercisesSets>
    implements ExercisesSetsService{
    @Resource
    private UserService userService;
    @Resource
    private ExercisesService exercisesService;
    @Resource
    private SetExercisesService setExercisesService;

    @Override
    public QueryWrapper<ExercisesSets> getQueryWrapper(ExercisesSetsQueryRequest exercisesSetsQueryRequest, User loginUser) {
        String title = exercisesSetsQueryRequest.getTitle();
        Integer setType = exercisesSetsQueryRequest.getSetType();
        String sortField = exercisesSetsQueryRequest.getSortField();
        String sortOrder = exercisesSetsQueryRequest.getSortOrder();
        QueryWrapper<ExercisesSets> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        queryWrapper.eq(ObjUtil.isNotNull(setType), "setType", setType);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), ASC.equals(sortOrder), sortField);
        boolean isAdmin = userService.isAdmin(loginUser);
        //非管理员则只能获取自己创建的
        if(!isAdmin){
            queryWrapper.eq(ObjUtil.isNotNull(loginUser.getId()),"userId", loginUser.getId());
        }
        return queryWrapper;
    }

    @Override
    public Page<ExercisesSets> listExercisesSetByPage(ExercisesSetsQueryRequest exercisesSetsQueryRequest, HttpServletRequest request) {
        long current = exercisesSetsQueryRequest.getCurrent();
        long pageSize = exercisesSetsQueryRequest.getPageSize();
        User loginUser = userService.getLoginUser(request);
        //2.查询结果
        Page<ExercisesSets> result = this.page(new Page<>(current, pageSize)
                , this.getQueryWrapper(exercisesSetsQueryRequest, loginUser));
        return result;
    }

    @Override
    public List<ExercisesVO> getExerciseVOList(Long setId) {
        //1.根据setId 得到 题目列表的和次序 （排序）
        QueryWrapper<SetExercises> setExercisesQueryWrapper = new QueryWrapper<SetExercises>()
                .eq("setId", setId)
                .orderBy(true, true, "position");
        //2.得到题目id列表
        List<Long> exerciseIdList = setExercisesService.list(setExercisesQueryWrapper).stream().map(SetExercises::getExerciseId).toList();
        //3.查询结果
        List<ExercisesVO> exercisesVOList = exercisesService.listByIds(exerciseIdList).stream().map(ExercisesVO::objToVO).toList();
        //4.返回结果
        return exercisesVOList;
    }

    /**
     * 删除套题 及其下的题目
     *
     * @param setId 套题id
     * @return 删除结果
     */
    @Override
    @Transactional
    public Boolean deleteExercisesSet(Long setId) {
        //1.根据setId 得到 题目列表的
        QueryWrapper<SetExercises> setExercisesQueryWrapper = new QueryWrapper<SetExercises>()
                .eq("setId", setId)
                .orderBy(true, true, "position");
        //2.得到题目id列表
        List<Long> exerciseIdList = setExercisesService.list(setExercisesQueryWrapper).stream().map(SetExercises::getExerciseId).toList();
        // 3.由于有外键的约束
        // 3.1我们得先删除set_exercises表中的数据
        QueryWrapper<SetExercises> deleteWrapper = new QueryWrapper<SetExercises>()
                .eq("setId", setId);
        boolean removed1 = setExercisesService.remove(deleteWrapper);
        //3.2再删除exercises表的数据
        boolean removed2 = exercisesService.removeByIds(exerciseIdList);
        //3.3 最后删除exercises_sets表的数据
        boolean removed3 = this.removeById(setId);
        ThrowUtils.throwIf(!removed1 || !removed2 || !removed3, ErrorCode.OPERATION_ERROR);
        return true;
    }
}




